<template>
    <div>
      <div class="echarts" :id="randomId" style="height: 100%"></div>
  </div>
</template>
<script type="text/ecmascript-6">
    import echarts from 'echarts'

    export default {
        name: 'echarts',
        props: {
            option: {
                type: Object,
                default(){
                    return {}
                }
            },
            randomId: {
                type: String,
                default() {
                    return 'myChart'
                }
            }
        },
        data() {
            return {}
        },

        mounted() {
            //# 1. 获取一个用于挂在 echarts 的 DOM 元素
            let $echartsDOM = document.getElementById(this.randomId);
            //# 2. 初始化
            //# 3. 设置配置项    let option = {...}
            //# 4. 为 echarts 指定配置   myEcharts.setOption(option)
            this.myEcharts = echarts.init($echartsDOM);
            this.checkAndSetOption()
        },
        beforeDestroy() { //组件卸载释放chart内存
            if(!!this.myEcharts) {
                this.myEcharts.clear(); //清空图表
                this.myEcharts.dispose(); //释放图表组件
                this.myEcharts = null;
            }
        },
        watch: {
            option(option){
                this.checkAndSetOption()
            }
        },
        methods: {
            checkAndSetOption(){
                function isValidOption(option){
                    return isObject(option) && !isEmptyObject(option)
                        && hasSeriesKey(option)
                        && isSeriesArray(option) && !isSeriesEmpty(option)
                }

                function isObject(option) {
                    return Object.prototype.isPrototypeOf(option)
                }

                function isEmptyObject(option){
                    return Object.keys(option).length === 0
                }

                function hasSeriesKey(option){
                    return !!option['series']
                }

                function isSeriesArray(option) {
                    return Array.isArray(option['series'])
                }

                function isSeriesEmpty(option){
                    return option['series'].length === 0
                }
                let option = this.option;    //配置等于父组件传过来的数据
                if(isValidOption(option)){
                    this.myEcharts.setOption(option);       //渲染出来
                    this.myEcharts.hideLoading();           //隐藏加载动画
                }else{
                    this.myEcharts.showLoading();           //加载动画
                }

            }
        }
    }
</script>
